import React from 'react'
import PropTypes from 'prop-types'
import { Menu, Icon, Tooltip } from 'antd'
// import { Link } from 'react-router-dom'
import router from 'umi/router'
import { config } from 'setting'
import { arrayToTree, queryArray, stringSize } from 'utils'
import pathToRegexp from 'path-to-regexp'

import styles from './Layout.less'

const { prefix } = config
const { SubMenu } = Menu
let openKeysFlag = false

const YQMenu = ({
  siderFold, isNavbar, navOpenKeys, changeOpenKeys, menu, location, switchSider, getProdMenu, closeProdMenu, switchSpreadAbled,
}) => {
  // 生成树状
  const menuTree = arrayToTree(menu.filter(_ => _.mpid !== '-1'), 'id', 'mpid')
  const levelMap = {}

  // 递归生成菜单
  const getMenus = (menuTreeN, siderFoldN) => {
    return menuTreeN.map((item) => {
      if (item.children) {
        if (item.mpid) {
          levelMap[item.id] = item.mpid
        }
        return (
          <SubMenu
            key={item.id}
            title={<span>
              {item.icon && <Icon type={item.icon} />}
              
              {(!siderFoldN || !menuTree.includes(item)) && 
                (stringSize(item.name) > 14? 
                <Tooltip placement="right" title={item.name}>
                  {item.name}
                </Tooltip> : item.name)
              }
            </span>}
          >
            {getMenus(item.children, siderFoldN)}
          </SubMenu>
        )
      }
      return (
        <Menu.Item key={item.id}>
          <div onClick={() => {handleMenu(item)}}>
            {item.icon && <Icon type={item.icon} />}
            {item.name}
          </div>
        </Menu.Item>
      )
    })
  }
  const menuItems = getMenus(menuTree, siderFold)

  // 保持选中
  const getAncestorKeys = (key) => {
    let map = {}
    const getParent = (index) => {
      const result = [String(levelMap[index])]
      if (levelMap[result[0]]) {
        result.unshift(getParent(result[0])[0])
      }
      return result
    }
    for (let index in levelMap) {
      if ({}.hasOwnProperty.call(levelMap, index)) {
        map[index] = getParent(index)
      }
    }
    return map[key] || []
  }

  const onOpenChange = (openKeys) => {
    if (navOpenKeys.length) changeOpenKeys([]), openKeysFlag = true
    const latestOpenKey = openKeys.find(key => !navOpenKeys.includes(key))
    const latestCloseKey = navOpenKeys.find(key => !openKeys.includes(key))
    let nextOpenKeys = []
    if (latestOpenKey) {
      nextOpenKeys = getAncestorKeys(latestOpenKey).concat(latestOpenKey)
    }
    if (latestCloseKey) {
      nextOpenKeys = getAncestorKeys(latestCloseKey)
    }
    changeOpenKeys(nextOpenKeys)
  }

  let menuProps = !siderFold ? {
    onOpenChange,
    openKeys: navOpenKeys,
  } : {}


  // 寻找选中路由
  const findSelectedRoute = () => {
    let currentMenu
    for (let item of menu) {
      if (item.link_to && pathToRegexp(item.link_to).exec(location.pathname)) {
        if (!navOpenKeys.length && item.mpid && !openKeysFlag) changeOpenKeys([String(item.mpid)])
        currentMenu = item
        break
      }
    }
    const getPathArray = (array, current, pid, id) => {
      let result = [String(current[id])]
      const getPath = (item) => {
        if (item && item[pid]) {
          if (item[pid] === '-1') {
            result.unshift(String(item['bpid']))
          } else {
            result.unshift(String(item[pid]))
            getPath(queryArray(array, item[pid], id))
          }
        }
      }
      getPath(current)
      return result
    }
    if (currentMenu) {
      window.defaultSelectedKeys = getPathArray(menu, currentMenu, 'mpid', 'id')
    }
  }
  if( window.localStorage.getItem(`${prefix}lastMenuType`) !== '0' ) findSelectedRoute()

  // 菜单点击
  const handleMenu = (item) => {
    window.localStorage.setItem(`${prefix}lastMenuType`, `${item.link_type}`)  //主菜单最后一次执行方式
    switch (item.link_type) {
      case "0":     // 展开次级菜单
        getProdMenu(item.id)
        switchSpreadAbled(true)
        window.defaultSelectedKeys = [item.mpid, item.id]
        break

      case "1":    // 内链跳转(无参数)
        closeProdMenu()  //关闭次级菜单
        switchSpreadAbled(false)  //次级菜单不可展开
        router.push(`${item.link_to}`)
        break

      case "2":    // 外链跳转(无参数)
        closeProdMenu()
        switchSpreadAbled(false)
        window.location.href=`${item.link_to}`
        break

      default:
        break
    }
  }

  return (
    <div>
      {!isNavbar && 
        <div className={styles.switchsider} onClick={switchSider}>
        <Icon type={siderFold? 'menu-unfold': 'menu-fold'} />
      </div>}
      <Menu
        {...menuProps}
        mode={siderFold ? 'vertical' : 'inline'} theme='dark'
        selectedKeys={window.defaultSelectedKeys}
      >
        {menuItems}
      </Menu> 
    </div>
  )
}

YQMenu.propTypes = {
  menu: PropTypes.array,
  siderFold: PropTypes.bool,
  isNavbar: PropTypes.bool,
  navOpenKeys: PropTypes.array,
  changeOpenKeys: PropTypes.func,
  location: PropTypes.object,
  switchSider: PropTypes.func,
  getProdMenu: PropTypes.func,
  closeProdMenu: PropTypes.func,
  switchSpreadAbled: PropTypes.func,
}

export default YQMenu